<template>
  <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()" style="margin-top: 10px;">
    <el-form-item>
      <el-input v-model="dataForm.searchName" type="text" clearable placeholder="请输入系列名称/产品型号"
        style="width: 282px;margin-right: 20px;"></el-input>
      <el-button @click="getDataList()" style="background: rgba(22, 119, 255, 1);color: #fff;border-radius: 5px;">{{
        $t("query") }}</el-button>
    </el-form-item>
    <div class="formlist">
      <div style="font-size: 14px; font-weight: 600;margin-bottom: 22px;">选择产品</div>
      <div class="formselect">
        <div class="formname">产品分类</div>
        <el-cascader :options="classOptions" clearable :props="cascaderProps" style="width: 500px;"
          v-model="selectedClassPath" @change="handleClassChange" placeholder="请选择分类">
        </el-cascader>
      </div>
      <div class="formselect">
        <div class="formname">产品品牌</div>
        <el-select v-model="dataForm.brandId" placeholder="请选择品牌" filterable style="width: 500px;" clearable>
          <el-option v-for="item in brandOptions" :key="item.id" :label="item.brandName" :value="item.id"></el-option>
        </el-select>
      </div>
      <div class="formselect">
        <div class="formname">产品状态</div>
        <el-checkbox-group v-model="ifValids" multiple @change="onIfValidChange">
          <el-checkbox label="0" size="large">在售</el-checkbox>
          <el-checkbox label="2" size="large">停产</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="formselect" style="margin-bottom: 10px;">
        <div class="formname">上架状态</div>
        <el-checkbox-group v-model="isUp" multiple @change="onIsUpChange">
          <el-checkbox label="0" size="large">可上架</el-checkbox>
          <el-checkbox label="1" size="large">已上架</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <div class="search">共搜索到<span style="color: rgba(22, 119, 255, 1);"> {{ total }}</span>条记录</div>
    <div class="product-table">
      <div v-if="productSerieses.length === 0" style="text-align: center;">
        <img src="../../assets/images/select-productng.png" alt="">
      </div>
      <div v-else v-for="(series, index) in productSerieses" :key="index">
        <div class="product-series">
          <div>
            <p style="margin-left: 16px;font-size: 14px;">系列名称: {{ series.seriesName }}
              <span style="color: rgba(22, 119, 255, 1);margin-left: 10px;">{{ series.isUp === 1 ? '已上架' : "" }}</span>
            </p>
          </div>
          <div class="sale" :style="{ color: series.ifValid === 0 ? 'red' : 'gray' }">
            {{ series.ifValid === 0 ? '在售' : '停产' }}
          </div>
        </div>
        <div class="product-list">
          <div class="product-image">
            <img :src="series.mainImages" :alt="series.seriesName">
            <div class="product-details">
              <p>品牌名称: {{ series.brandName }}</p>
              <p>产品编号: {{ series.seriesCode }}</p>
              <p>{{ series.className }}</p>
            </div>
          </div>
          <div class="product-models">
            <div style="margin-right: 20px;margin-top: 14px;">产品型号</div>
            <div class="product-models">
              <span v-for="model in series.productNames?.split(',')" :key="model" class="model-item">{{ model }}</span>
            </div>
          </div>
          <div class="product-action">
            <el-button :disabled="!hasProductModels(series)" @click="addOrUpdateHandle(series)">报价</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px;" />
  </el-form>
  <!-- 弹窗, 新增 / 修改 -->
  <add-or-update :key="addKey" ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus"
import type { ComponentSize } from 'element-plus'
import { nextTick, reactive, ref, onActivated } from "vue";
import AddOrUpdate from "./product-quotation-list-add-or-update.vue";

// 分页相关变量
const page = ref(1);
const limit = ref(20);
const total = ref(0);

const dataForm = reactive({
  searchName: "",
  brandId: "",
  class1Id: "",
  class2Id: "",
  class3Id: "",
  ifValids: "0,2",
  isUp: "2"
})

// 定义判断是否有产品型号的方法
const hasProductModels = (series: Series) => {
  return series.productNames && series.productNames.trim().length > 0;
};

// 分页处理函数
const handleSizeChange = (val: number) => {
  limit.value = val;
  page.value = 1; // 当每页条数改变时，重置到第一页
  getDataList();
}

const handleCurrentChange = (val: number) => {
  page.value = val;
  getDataList();
}

const ifValids = ref(['0', '2']);
const isUp = ref(['0', '1']);

const cascaderProps = reactive({ value: "id", label: "className", children: "children", emitPath: true });

// 分类选项
const classOptions = ref<any[]>([]);
// 品牌选项
const brandOptions = ref<any[]>([]);
// 选中的分类路径
const selectedClassPath = ref<string[]>([]);
const handleClassChange = (value: string[]) => {
  dataForm.class1Id = value && value.length > 0 ? value[0] : "";
  dataForm.class2Id = value && value.length > 1 ? value[1] : "";
  dataForm.class3Id = value && value.length > 2 ? value[2] : "";
};

const onIfValidChange = (value: string[]) => {
  dataForm.ifValids = value.join(',');
  page.value = 1; // 筛选条件改变时重置到第一页
  getDataList();
};

const onIsUpChange = (value: string[]) => {
  if (value.length == 1) {
    dataForm.isUp = value[0];
  } else if (value.length == 2) {
    dataForm.isUp = '2';
  } else {
    dataForm.isUp = '';
  }
  page.value = 1; // 筛选条件改变时重置到第一页
  getDataList();
};

interface Series {
  id: number;
  mainImages: string;
  seriesName: string;
  brandName: string;
  seriesCode: string;
  className: string;
  productNames: string;
  ifValid: number;
  isUp: number;
}

const productSerieses = ref<Series[]>([]);

const getDataList = () => {
  const params = {
    ...dataForm,
    page: page.value,
    limit: limit.value
  };

  baseService.get('/noc/productseries/supplierSeriesList', params).then(res => {
    if (res && res.data) {
      productSerieses.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  }).catch(error => {
    // console.error('获取产品系列数据出错:', error);
    // ElMessage.error('获取产品系列数据出错');
  });
};

// 新增/修改相关
const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (series?: Series) => {
  if (!series?.productNames) {
    ElMessage.error('当前系列没有产品型号，不可报价');
    return;
  }
  addKey.value++;
  nextTick(() => {
    addOrUpdateRef.value.init(series?.id, series?.ifValid);
  });
};

// 获取分类列表
const getClassList = () => {
  baseService.get('/noc/nocclassify/list2').then(res => {
    classOptions.value = res.data || [];
  }).catch(error => {
    console.error('获取分类数据出错:', error);
    ElMessage.error('获取分类数据出错');
  });
};

// 获取品牌列表
const getBrandList = () => {
  baseService.get('/noc/productuserquotation/getBrandListByBrandIds', {
    page: 1,
    limit: 5000
  }).then(res => {
    if (res && res.data) {
      brandOptions.value = res.data;
    }
  });
};

const init = () => {
  getClassList();
  getBrandList();
  getDataList();

  // 重置表单数据
  dataForm.searchName = "";
  dataForm.brandId = "";
  dataForm.class1Id = "";
  dataForm.class2Id = "";
  dataForm.class3Id = "";
  dataForm.ifValids = "0,2";
  dataForm.isUp = "2";

  // 重置分页
  page.value = 1;
  limit.value = 20;

  // 设置checkbox组的值
  ifValids.value = ['0', '2'];
  isUp.value = ['0', '1'];

  // 清空产品列表
  productSerieses.value = [];

  // 重置分类选择
  selectedClassPath.value = [];
}

// 初始化
onActivated(() => {
  init();
});
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
  white-space: nowrap;
}

.el-select {
  width: 229px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.sale {
  color: rgba(212, 48, 48, 1);
  font-size: 14px;
  line-height: 50px;
  margin-right: 27px;
}

.formlist {
  padding: 23px 20px 0px 20px;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  border: 1px dashed rgba(31, 31, 31, 0.36);
  margin-top: 10px;
}

.formname {
  font-size: 13px;
  width: 110px;
  text-align: left;
}

.formselect {
  margin-bottom: 20px;
  display: flex;
  line-height: 36px;
}

.search {
  font-size: 14px;
  font-weight: 600;
  color: rgba(56, 56, 56, 1);
  margin: 19px 0px 17px 15px;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
}

.product-series {
  display: flex;
  justify-content: space-between;
  background: rgba(239, 245, 255, 1);
  height: 50px;
}

.product-list {
  display: flex;
  justify-content: space-between;
  margin: 20px 20px 20px 20px;
}

.product-image {
  width: 40%;
  display: flex;
}

.product-image img {
  width: 100px;
  height: 100px;
  object-fit: contain;
}

.product-details {
  font-size: 14px;
  margin-left: 30px;
}

.product-models {
  width: 50%;
  display: flex;
  flex-wrap: wrap;
}

.model-item {
  width: calc(33.33% - 30px);
  margin-bottom: 10px;
}

.product-action button {
  background-color: #007BFF;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.product-action button:hover {
  background-color: #0056b3;
}

::v-deep .el-table .cell {
  white-space: nowrap;
  height: 30px;
  line-height: 30px;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  justify-content: end;
}
</style>
